package com.example.config;

import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.integration.channel.ExecutorChannel;
import org.springframework.integration.core.MessageProducer;
import org.springframework.integration.mqtt.core.DefaultMqttPahoClientFactory;
import org.springframework.integration.mqtt.core.MqttPahoClientFactory;
import org.springframework.integration.mqtt.inbound.MqttPahoMessageDrivenChannelAdapter;
import org.springframework.messaging.MessageChannel;

import java.util.concurrent.Executors;

@Configuration
public class MqttConfiguration {
    @Value("${spring.mqtt.broker-url}")
    private String brokerUrl;

    @Value("${spring.mqtt.username}")
    private String username;

    @Value("${spring.mqtt.password}")
    private String password;

    @Value("${spring.mqtt.keep-alive-interval}")
    private int keepAliveInterval;

    @Value("${spring.mqtt.clean-session}")
    private boolean isCleanSession;

    @Value("${spring.mqtt.automatic-reconnect}")
    private boolean isAutoReconn;

    @Value("${spring.mqtt.client-id}")
    private String clientId;

    @Value("${spring.mqtt.default-topic}")
    private String defaultTopic;

    private MqttPahoMessageDrivenChannelAdapter adapter;

    @Bean
    public MqttConnectOptions mqttConnectOptions() {
        MqttConnectOptions options = new MqttConnectOptions();
        options.setServerURIs(new String[]{brokerUrl});
        options.setUserName(username);
        options.setPassword(password.toCharArray());
        options.setAutomaticReconnect(isAutoReconn); // 启用自动重连
        options.setCleanSession(isCleanSession);
        options.setKeepAliveInterval(keepAliveInterval);
        return options;
    }

    @Bean
    public MqttPahoClientFactory mqttClientFactory() {
        DefaultMqttPahoClientFactory factory = new DefaultMqttPahoClientFactory();
        factory.setConnectionOptions(mqttConnectOptions());
        return factory;
    }

    @Bean
    public MessageChannel mqttInputChannel() {
        return new ExecutorChannel(Executors.newFixedThreadPool(10));
    }

    // 订阅适配器（自动启动）
    @Bean
    public MessageProducer inbound(MqttPahoClientFactory clientFactory) {
        adapter = new MqttPahoMessageDrivenChannelAdapter(
                clientId,
                clientFactory,
                defaultTopic
        );
        adapter.setOutputChannel(mqttInputChannel());
        adapter.setQos(1);  // QoS级别
        return adapter;
    }

    // 动态添加订阅
    public void addTopic(String topic, int qos) {
        adapter.addTopic(topic, qos);
    }
}
